// pages/volunteer/checkin-records.js
Page({
  data: {
    // 统计数据
    totalDays: 0,
    continuousDays: 0,
    totalPoints: 0,
    
    // 筛选相关
    currentTab: 'all',
    allRecords: [],
    filteredRecords: [],
    
    // 分页相关
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false
  },

  onLoad(options) {
    this.loadRecords();
  },

  onShow() {
    this.refreshData();
  },

  // 加载记录
  loadRecords() {
    const checkinRecords = wx.getStorageSync('checkinRecords') || [];
    const processedRecords = this.processRecords(checkinRecords);
    
    this.setData({
      allRecords: processedRecords,
      totalDays: checkinRecords.length,
      totalPoints: checkinRecords.reduce((sum, record) => sum + record.points, 0),
      continuousDays: this.calculateContinuousDays(checkinRecords)
    });
    
    this.filterRecords();
  },

  // 处理记录数据
  processRecords(records) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    
    return records.map(record => {
      const date = new Date(record.date);
      const day = date.getDate();
      const month = months[date.getMonth()];
      const weekday = weekdays[date.getDay()];
      
      return {
        ...record,
        day,
        month,
        weekday,
        status: this.getRecordStatus(record)
      };
    }).sort((a, b) => new Date(b.date) - new Date(a.date));
  },

  // 获取记录状态
  getRecordStatus(record) {
    const today = new Date().toISOString().split('T')[0];
    if (record.date === today) {
      return '今日';
    }
    
    const recordDate = new Date(record.date);
    const now = new Date();
    const diffDays = Math.floor((now - recordDate) / (1000 * 60 * 60 * 24));
    
    if (diffDays === 1) {
      return '昨日';
    } else if (diffDays <= 7) {
      return `${diffDays}天前`;
    } else {
      return record.date;
    }
  },

  // 计算连续签到天数
  calculateContinuousDays(records) {
    if (records.length === 0) return 0;
    
    const sortedRecords = records.sort((a, b) => new Date(b.date) - new Date(a.date));
    let continuousDays = 0;
    let currentDate = new Date();
    
    for (let i = 0; i < sortedRecords.length; i++) {
      const recordDate = new Date(sortedRecords[i].date);
      const diffDays = Math.floor((currentDate - recordDate) / (1000 * 60 * 60 * 24));
      
      if (diffDays === continuousDays) {
        continuousDays++;
        currentDate = recordDate;
      } else {
        break;
      }
    }
    
    return continuousDays;
  },

  // 筛选记录
  filterRecords() {
    const { currentTab, allRecords } = this.data;
    let filtered = [];
    
    switch (currentTab) {
      case 'week':
        filtered = this.filterByWeek(allRecords);
        break;
      case 'month':
        filtered = this.filterByMonth(allRecords);
        break;
      default:
        filtered = allRecords;
    }
    
    this.setData({
      filteredRecords: filtered.slice(0, this.data.pageSize),
      hasMore: filtered.length > this.data.pageSize,
      page: 1
    });
  },

  // 按周筛选
  filterByWeek(records) {
    const now = new Date();
    const weekStart = new Date(now);
    weekStart.setDate(now.getDate() - now.getDay());
    weekStart.setHours(0, 0, 0, 0);
    
    return records.filter(record => {
      const recordDate = new Date(record.date);
      return recordDate >= weekStart;
    });
  },

  // 按月筛选
  filterByMonth(records) {
    const now = new Date();
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
    
    return records.filter(record => {
      const recordDate = new Date(record.date);
      return recordDate >= monthStart;
    });
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
    this.filterRecords();
  },

  // 加载更多
  loadMore() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({ loading: true });
    
    setTimeout(() => {
      const { currentTab, allRecords, page, pageSize } = this.data;
      let filtered = [];
      
      switch (currentTab) {
        case 'week':
          filtered = this.filterByWeek(allRecords);
          break;
        case 'month':
          filtered = this.filterByMonth(allRecords);
          break;
        default:
          filtered = allRecords;
      }
      
      const newRecords = filtered.slice(0, (page + 1) * pageSize);
      
      this.setData({
        filteredRecords: newRecords,
        hasMore: filtered.length > (page + 1) * pageSize,
        page: page + 1,
        loading: false
      });
    }, 500);
  },

  // 刷新数据
  refreshData() {
    this.loadRecords();
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '我的签到记录',
      path: '/pages/volunteer/checkin-records',
      imageUrl: '/images/share-records.png'
    };
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载
  onReachBottom() {
    this.loadMore();
  }
});
